from fastapi import APIRouter, HTTPException
from app.core.db import SessionDep
from app.models.user import User
from app.schemas.user import UserCreate, UserResponse, UserUpdate
from app.utils.pwd_utils import get_password_hash
from sqlmodel import select

router = APIRouter(prefix="/users", tags=["用户管理"])  # 创建APIRouter实例


@router.get("/list", summary="获取用户列表", response_model=list[UserResponse])
async def get_users(
    db: SessionDep,
    skip: int = 0,
    limit: int = 10,
) -> list[UserResponse]:
    users = db.exec(select(User).where(User.deleted == False)).all()
    return users


@router.post("/", summary="创建新用户", response_model=UserResponse)
async def create_user(user_create: UserCreate, db: SessionDep) -> UserResponse:
    db_obj = User.model_validate(
        user_create, update={"password": get_password_hash(user_create.password)}
    )
    db.add(db_obj)
    db.commit()
    db.refresh(db_obj)
    return UserResponse.model_validate(db_obj)


@router.get("/{user_id}", summary="根据ID获取用户", response_model=UserResponse)
async def get_user_by_id(user_id: int, db: SessionDep) -> UserResponse:
    user = db.exec(
        select(User).where(User.id == user_id, User.deleted == False)
    ).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户未找到")
    return UserResponse.model_validate(user)


@router.delete("/{user_id}", summary="根据ID删除用户", response_model=dict)
async def delete_user_by_id(user_id: int, db: SessionDep) -> dict:
    user = db.exec(
        select(User).where(User.id == user_id, User.deleted == False)
    ).first()
    if user:
        # 逻辑删除
        user.deleted = True
        db.add(user)
        db.commit()
        return {"message": "用户已删除"}
    raise HTTPException(status_code=404, detail="用户不存在")


@router.put("/{user_id}", summary="根据ID更新用户信息", response_model=UserResponse)
async def update_user_by_id(
    user_id: int, user_update: UserUpdate, db: SessionDep
) -> UserResponse:
    user = db.get(User, user_id)
    if user and not user.deleted:
        user_data = user_update.model_dump(exclude_unset=True)
        for key, value in user_data.items():
            if key == "password":
                value = get_password_hash(value)
            setattr(user, key, value)
        db.add(user)
        db.commit()
        db.refresh(user)
        return UserResponse.model_validate(user)
    raise HTTPException(status_code=404, detail="ID 错误或者用户不存在")
